package com.gutetec.cms.bmc.db.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.dropwizard.hibernate.AbstractDAO;

/**
 * <Function brief> <Function details>
 * 
 * @author Administrator
 * @version [Version, 2016-2-17]
 * @see [Classs/Method]
 * @since [Product/Model Version]
 */
public class FmDbDAO<E> extends AbstractDAO<E> {

  private static final Logger logger = LoggerFactory.getLogger(FmDbDAO.class);
  private SessionFactory sessionFactory;
  protected Session session;

  /**
   * <>
   */
  public FmDbDAO(SessionFactory sessionFactory) {
    super(sessionFactory);
    this.sessionFactory = sessionFactory;
  }

  protected Session currentSession() {
    return this.session;
  }

  protected void beginTransaction() {
    this.session = this.sessionFactory.openSession();
    this.session.beginTransaction();
  }

  protected void closeTransaction() {
    this.session.getTransaction().commit();
    this.session.close();
  }

  public Object save(Object object) {

    try {
      beginTransaction();
      session.save(object);
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    } finally {
      closeTransaction();
    }

    return object;
  }

  public void delete(Object object) {
    try {
      beginTransaction();
      session.delete(object);
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    } finally {
      closeTransaction();
    }
  }

  public void update(Object object) {
    try {
      beginTransaction();
      session.update(object);
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
    } finally {
      closeTransaction();
    }
  }
}
